﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using PMS.Entity;

namespace PMS.Entity
{
    public class BaseEntityCollection<T> : BindingList<T>, IBaseEntity where T : IBaseEntity
    {
        public BaseEntityCollection()
            : this(null)
        { }

        public BaseEntityCollection(IEnumerable<T> list)
        { 
            this.AddRange(list);
            removeItems = new List<T>();
        }

        public virtual void AddRange(IEnumerable<T> list)
        {
            if (list != null)
            {
                foreach (var item in list)
                {                    
                    (item as BaseEntity).RowStatus = (int)RowStatus.Update;
                    base.Items.Add(item);
                }
            }
        }

        public virtual void RemoveAt(int index)
        {
            T item = this[index];
            (item as BaseEntity).RowStatus = (int)RowStatus.Delete;
            removeItems.Add(this[index]);
            base.RemoveAt(index);
        }

        public virtual void Clear()
        {
            removeItems.Clear();
            base.Clear();
        }

        private List<T> removeItems = null;
        public List<T> RemoveRows
        {
            get { return removeItems; }
        }

        public object Clone()
        {
            //return base.MemberwiseClone();
            var newInstance = Activator.CreateInstance<BaseEntityCollection<T>>();

            foreach (var item in this) newInstance.Add((T)item.Clone());

            return newInstance;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected override void OnListChanged(ListChangedEventArgs e)
        {
            base.OnListChanged(e);

            if (e.ListChangedType == ListChangedType.ItemAdded)
            {
                //Items.RemoveAt(e.NewIndex);
                this.EndNew(e.NewIndex);
                //(Items[e.NewIndex] as BaseEntity) = (Items[e.NewIndex] as BaseEntity).Clone();
                (Items[e.NewIndex] as BaseEntity).RowStatus= (int)RowStatus.New;
            }
            
            if (e.ListChangedType == ListChangedType.ItemChanged)
            {
                if (this.PropertyChanged != null)
                {
                    this.PropertyChanged(this[e.NewIndex], new PropertyChangedEventArgs(e.PropertyDescriptor.Name));
                }
            }
        }
    }

}
